import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  getters: {
    totalCount (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    totalPrice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
    }
  },
  mutations: {
    setList (state, list) {
      state.list = list
    },

    updateGoodsCount (state, goods) {
      const goodsObj = state.list.find(item => item.id === goods.id)
      goodsObj.count = goods.count
    }
  },
  actions: {
    async setCartList (ctx) {
      const res = await axios.get('http://localhost:3000/cart')
      ctx.commit('setList', res.data)
    },

    async updateGoodsCount (ctx, goods) {
      await axios.patch(`http://localhost:3000/cart/${goods.id}`, { count: goods.count })
      ctx.commit('updateGoodsCount', { id: goods.id, count: goods.count })
    }
  }
}
